package com.yr.ryjk.businessengine;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.yr.ryjk.businessengine.task.BaseOnceTask;
import com.yr.ryjk.businessengine.task.BaseTask;
import com.yr.ryjk.businessengine.task.BaseTaskManager;
import com.yr.ryjk.businessengine.task.BaseTimerTask;

/**
 * 事务引擎
 * @author Rick
 * 
 */
public class BusinessEngine {
	private static Logger logger = Logger.getLogger(BusinessEngine.class);
	// 线程池
	private static ExecutorService threadPool = null;
	// 任务管理器
	private static BaseTaskManager taskManager = null;
	private static Timer timer;
	private static boolean isContinue=true;

	static {
		threadPool = Executors.newCachedThreadPool();
		taskManager = new BaseTaskManager();
		timer = new Timer();
	}

	/**
	 * 向事务引擎递交任务
	 * @param task
	 */
	public static void addTask(BaseTask task) {
		taskManager.add(null, task, true);
	}

	/**
	 * 在同一个进程中执行任务
	 * @param task
	 */
	public static void runTask(final BaseTask task) {
		// ask thread pool to run a new task
		threadPool.execute(new Runnable() {
			public void run() {
				try {
					task.exec();
				} catch (Exception e) {
					e.printStackTrace();
				}
				BaseTask next = task.getNext();
				if (next != null) {
					taskManager.add(task, next, true);// 将下个任务递交给事务引擎
				}
				// 删除持久化文件,避免BaseTimerTask的持久化文件被删除
				if (next != task) {
					taskManager.removeStore(task);
				}
			}
		});
	}

	/**
	 * 执行定时任务
	 * @param task
	 */
	private static void runTimerTask(final BaseTimerTask task) {
		timer.schedule(new TimerTask() {
			public void run() {
				runTask(task);
			}
		}, task.getDelay());

	}

	/**
	 * 开启事务引擎
	 */
	public static void start() {
		taskManager.restore();

		logger.info("事务引擎BussinessEngine started...");
		new Thread(new Runnable() {
			public void run() {
				// restore from manager
				while (isContinue) {
					System.out.println("while true..."+isContinue);
					// get task from manager
					BaseTask task = (BaseTask) taskManager.getTask();
					if (task instanceof BaseOnceTask) {
						runTask((BaseOnceTask) task);
					} else if (task instanceof BaseTimerTask) {
						runTimerTask((BaseTimerTask) task);
					}
				}
			}
		}).start();
	}
	
	/**
	 * 关闭事务引擎
	 */
	public static void close() {
		isContinue=false;
	}
}